package cn.bone.mqtt.demo03;

import com.alibaba.fastjson.JSON;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by MD-01 on 2017/4/25.
 */
public class Client04 {
    private static Logger logger = LoggerFactory.getLogger(Client04.class);

    public static void main(String[] args) throws MqttException {
        //String host = "tcp://127.0.0.1:61613";
        String host = "tcp://127.0.0.1:1883";
        MqttClient client = new MqttClient(host,"clientId-04",
                new MqttDefaultFilePersistence("d:/mqtt"));
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("admin");
        options.setPassword("password".toCharArray());
        //false:服务端不清除session,true:服务端清除session
        options.setCleanSession(false);
        //设置自动重新连接
        options.setAutomaticReconnect(true);
        options.setWill("client/disOnline","client04,disOnline".getBytes(),2,true);
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                logger.info("连接丢失:"+cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                logger.info("收到消息.topic:"+topic+
                        "  msg:"+ new String(message.getPayload(),"UTF-8")+
                        "  qos:" + message.getQos()+
                        "  id:" + message.getId() +
                        "  duplicate(重复):" + message.isDuplicate() +
                        "  retained(保留):" + message.isRetained());
                //client.messageArrivedComplete(message.getId(),message.getId());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                logger.info("发送完成:"+ JSON.toJSONString(token));
            }
        });
        client.connect(options);
        client.subscribe("topic/client-04",1);
        client.subscribe("topic/all",1);
    }
}
